<template>
  <div class="about">
    <div class="box_a">
      <!-- 九宫格 -->
      <div class="a_left" style="display: flex; flex-wrap: wrap; background-color: #000">
        <div v-for="i in spilt" :key="i" class="play-box" :style="liveStyle" @click="btn_xh(i)">
          <div v-if="!videoUrl[i - 1]" style="
              color: #ffffff;
              font-size: 0.3rem;
              font-weight: bold;
              width: 100%;
              height: 99%;
            " :class="{ redborder: playerIdx == i - 1 }" class="no-video">
            <span>{{ i }}</span>
          </div>
          <!-- AI识别 -->
          <div class="ai-box" style="width: 100%; height: 100%; border: none" v-if="videoUrl[i - 1] && AItxt == 'AI识别'"
            ref="playerRefs">
            <iframe style="width: 100%; height: 100%; border: none" :src="'https://qilihai.baohuqu.net:8080/vis/detect_video/' +
              (changeHikId ? changeHikId : hikId[i - 1])
              " @screenshot="shot" allowfullscreen="true"></iframe>
            <div class="zhezhao" style="width: 100%; height: 100%" :class="{ redborder: playerIdx == i - 1 }"
              @destroy="destroy"></div>
          </div>
          <!-- 普通监控 -->
          <player ref="playerRefs" v-if="videoUrl[i - 1] && AItxt == '普通监控'" :videoUrl="changeVideo || videoUrl[i - 1]"
            fluent autoplay @screenshot="shot" @destroy="destroy" :class="{ redborder: playerIdx == i - 1 }" />
        </div>
      </div>
      <!-- 监控列表 -->
      <div class="a_right">
        <div class="top_box">
          <p class="p1">设备情况</p>
        </div>
        <div class="btn_box">
          <button class="btn1" v-for="(item, index) in btnList" :class="index == setAtab ? 'btn_Select' : ''"
            @click="btn_toggle(index)">
            {{ item.btn_name }}
          </button>
          <!-- <button class="btn1 btn_AI" @click="toggle_AI">{{ AItxt }}</button> -->
          <div class="btn_radio">
            <input type="radio" value="识别框" :checked="isChecked" @click="toggleRadioButton" />
            <label for="识别框" class="txts">识别框</label><br />
          </div>
        </div>
        <div class="righttop_foot">
          <!-- 树形控件 -->
          <div class="listTree" style="width: 100%" v-if="setAtab == 1">
            <el-tree style="width: 100%" :data="treeData" :props="defaultProps" @node-click="handleNodeClick" />
          </div>
          <!-- UI设计版 -->
          <el-table :data="tableData" style="width: 100%" height="4.41rem" v-if="setAtab == 0">
            <el-table-column prop="onLine" label="设备状态" width="">
              <template #default="scope">
                <div class="sxt">
                  <img src="../assets/img/sxt.png" alt="" />
                  <span>{{
                    scope.row.deviceStatus == 1 ? "在线" : "离线"
                  }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="deviceName" label="摄像头名称" width="" />
            <el-table-column label="操作" width="">
              <template #default="scope">
                <img src="../assets/img/jt.png" alt="" style="width: 0.26rem; height: 0.14rem; cursor: pointer"
                  @click="btn_bf(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 云台控制 -->
        <div class="right_bottom">
          <div class="top_box">
            <p class="p1">云台控制</p>
          </div>
          <div class="holder">
            <!-- 圆 -->
            <div class="round">
              <div class="r1">
                <img src="../assets/img/shang.png" alt="" @mousedown.left="btn_direction('up', 'UP')"
                  @mouseup.left="btn_direction('stop')" />
              </div>
              <div class="r3">
                <img src="../assets/img/zuo.png" alt="" @mousedown.left="btn_direction('left', 'LEFT')"
                  @mouseup.left="btn_direction('stop')" />
                <img src="../assets/img/you.png" alt="" @mousedown.left="btn_direction('right', 'RIGHT')"
                  @mouseup.left="btn_direction('stop')" />
              </div>
              <div class="r1">
                <img src="../assets/img/xia.png" alt="" @mousedown.left="btn_direction('down', 'DOWN')"
                  @mouseup.left="btn_direction('stop')" />
              </div>
            </div>
            <!-- 放大缩小 -->
            <div class="control">
              <div class="big" @mousedown.left="btn_direction('zoomin', 'ZOOM_IN')"
                @mouseup.left="btn_direction('stop')">
                <el-icon class="icons">
                  <ZoomIn />
                </el-icon>
                <span style="margin-left: 0.05rem">放大</span>
              </div>
              <div class="small" @mousedown.left="btn_direction('zoomout', 'ZOOM_OUT')"
                @mouseup.left="btn_direction('stop')">
                <el-icon class="icons">
                  <ZoomOut />
                </el-icon>
                <span style="margin-left: 0.05rem">缩小</span>
              </div>
            </div>
            <!-- 线 -->
            <hr class="style1" />
            <!-- 画面选择 -->
            <div class="hm">
              <span>分屏选择</span>
              <el-icon class="eicon" :class="{ active: spilt == 1 }" @click="changeGrid(1)">
                <FullScreen />
              </el-icon>
              <el-icon class="eicon" :class="{ active: spilt == 4 }" @click="changeGrid(4)">
                <Menu />
              </el-icon>
              <el-icon class="eicon" :class="{ active: spilt == 9 }" @click="changeGrid(9)">
                <Grid />
              </el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 监控画面 B -->
</template>
<script setup>
import {
  onMounted,
  onUnmounted,
  ref,
  watch,
  computed,
  nextTick,
  reactive,
} from "vue";
import player from "@/components/plays.vue";
import { useRoute } from "vue-router";
import axios from "axios";
import {
  Search,
  FullScreen,
  Menu,
  Grid,
  ZoomIn,
  ZoomOut,
} from "@element-plus/icons-vue";
import {
  getMonitorListApi,
  getMonitorListApi2,
  getPtzControlApi,
  getAnimalMonitorListApi,
  NewgetPtzControlApi2,
  NewgetPtzControlApi3,
  plays,
  getplay
} from "@/utils/api";
import { ElMessage } from "element-plus";
let treeData = ref([]);
let tableData = ref([]);
let setAtab = ref(0);
let videoUrl = ref([""]);
let spilt = ref(4);
let playerIdx = ref(0);
let updateLooper = ref(0);
let loading = ref(false);
let route = useRoute();
let manageSite;
let AItxt = ref("普通监控");
let btnList = [
  {
    btn_name: "鸟类监控",
    id: 0,
  },
  {
    btn_name: "AR全景",
    id: 1,
  },
];
const playerRefs = ref([]);
const liveStyle = computed(() => {
  let style = { width: "100%", height: "100%" };
  switch (spilt.value) {
    case 4:
      style = { width: "50%", height: "50%" };
      break;
    case 9:
      style = { width: "33.3%", height: "33.3%" };
      break;
  }
  return style;
});


onMounted(() => {
  manageSite = window.sessionStorage.getItem("manageSite");
  getMonitorList();
}),
  watch(spilt, (newValue) => {
    // console.log("切换画幅;" + newValue);
    nextTick(() => {
      for (let i = 1; i <= newValue; i++) {
        const players = playerRefs.value["player" + i];
        // console.log(players , '监听');
        if (players) {
          if (Array.isArray(players)) {
            players[0].resize();
          } else {
            players.resize();
          }
        }
      }
    });
    window.localStorage.setItem("split", newValue);
  });
watch(
  () => route.fullPath,
  () => checkPlayByParam()
);
onUnmounted(() => {
  clearTimeout(updateLooper.value);
});
const destroy = (idx) => {
  clear(idx.substring(idx.length - 1));
};

const goFullScreen = (event) => {
  // console.log(event, 'eeeeeeeeeeeeeee');
  const iframe = event.target;
  // console.log(iframe, '45456');
  if (iframe.requestFullscreen) {
    iframe.requestFullscreen();
  } else if (iframe.mozRequestFullScreen) {
    /* Firefox */
    iframe.mozRequestFullScreen();
  } else if (iframe.webkitRequestFullscreen) {
    /* Chrome, Safari & Opera */
    iframe.webkitRequestFullscreen();
  } else if (iframe.msRequestFullscreen) {
    /* IE/Edge */
    iframe.msRequestFullscreen();
  }
};
const toggle_AI = () => {
  AItxt.value == "普通监控"
    ? (AItxt.value = "AI识别")
    : (AItxt.value = "普通监控");
};
let isChecked = ref(false);
const toggleRadioButton = () => {
  isChecked.value = !isChecked.value;
  if (isChecked.value == false) {
    AItxt.value = "普通监控";
  } else {
    AItxt.value = "AI识别";
  }
};
let hikId = ref([""]);
let changeHikId = ref("");
const sendDevicePush = async (itemData) => {
  try {
    save(itemData);
    let hikIds = itemData.hikIds;
    let idxTmp = playerIdx.value;
    loading.value = true;
    hikId.value[idxTmp] = itemData.hikIds;
    const response = await plays(hikIds)
    console.log(response, 'response');
    if (response.data.code == 200) {
   
      
      let videoUrl;
      console.log(response, 'response');
      let originalUrl = response.data.data.ws_flv;
      let newBase = "https://qilihai.baohuqu.net:8080/gb";
      function replaceBaseUrl(url, newBase, separator) {
        let index = url.indexOf(separator);
        if (index !== -1) {
          let newUrl = newBase + url.substring(index);
          return newUrl;
        } else {
          console.log(`标识符 '${separator}' 未找到`);
          return url; // 如果没有找到分隔符，返回原始 URL
        }
      }
      response.data.data.ws_flv = replaceBaseUrl(originalUrl, newBase, "/rtp");
      response.data.data.wss_flv = replaceBaseUrl(originalUrl, newBase, "/rtp");
      if (location.protocol === "https:") {
        videoUrl = response.data.data.wss_flv;
      } else {
        videoUrl = response.data.data.ws_flv;
      }
      itemData.playUrl = videoUrl;
      setPlayUrl(videoUrl, idxTmp);
    } else {
    }
  } catch (error) {
    console.error("Error:", error);
  } finally {
    loading.value = false;
  }
};
// AR
const sendDevicePush1 = async (itemData) => {
  try {
    save(itemData);
    let deviceId = itemData.deviceId;
    let channelId = itemData.channelId;
    // console.log("通知设备推流1：" + deviceId + " : " + channelId);
    let idxTmp = playerIdx.value;
    loading.value = true;
    const response = await getplay(deviceId, channelId);
    if (response.data.code == 0) {
      let videoUrl;
      console.log(response, 'response');
      let originalUrl = response.data.data.ws_flv;
      let newBase = "https://qilihai.baohuqu.net:8080/gb";
      function replaceBaseUrl(url, newBase, separator) {
        let index = url.indexOf(separator);
        if (index !== -1) {
          let newUrl = newBase + url.substring(index);
          return newUrl;
        } else {
          console.log(`标识符 '${separator}' 未找到`);
          return url; // 如果没有找到分隔符，返回原始 URL
        }
      }
      response.data.data.ws_flv = replaceBaseUrl(originalUrl, newBase, "/rtp");
      response.data.data.wss_flv = replaceBaseUrl(originalUrl, newBase, "/rtp");
      
      if (location.protocol === "https:") {
        videoUrl = response.data.data.wss_flv;
      } else {
        videoUrl = response.data.data.ws_flv;
      }
        console.log(videoUrl, 'videoUrl');
        
      itemData.playUrl = videoUrl;
      setPlayUrl(videoUrl, idxTmp);
    } else {
    }



    // if (response.data.code === 0 && response.data.data) {
    //   let videoUrl;
    //   if (location.protocol === "https:") {
    //     videoUrl = response.data.data.wss_flv;
    //   } else {
    //     videoUrl = response.data.data.ws_flv;
    //   }
    //   console.log(videoUrl, 'videoUrl');
    //   itemData.playUrl = videoUrl;
    //   setPlayUrl(videoUrl, idxTmp);
    // } else {}
  } catch (error) {
    // console.error("Error:", error);
  } finally {
    loading.value = false;
  }
};
const setPlayUrl = (url, idx) => {
  videoUrl.value[idx] = url;
  setTimeout(() => {
    window.localStorage.setItem("videoUrl", JSON.stringify(videoUrl.value));
  }, 100);
};

const checkPlayByParam = () => {
  // console.log(route.query);
};
const shot = (e) => {
  var base64ToBlob = function (code) {
    let parts = code.split(";base64,");
    let contentType = parts[0].split(":")[1];
    let raw = window.atob(parts[1]);
    let rawLength = raw.length;
    let uInt8Array = new Uint8Array(rawLength);
    for (let i = 0; i < rawLength; ++i) {
      uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], {
      type: contentType,
    });
  };
  let aLink = document.createElement("a");
  let blob = base64ToBlob(e); //new Blob([content]);
  let evt = document.createEvent("HTMLEvents");
  evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
  aLink.download = "截图";
  aLink.href = URL.createObjectURL(blob);
  aLink.click();
};

const save = (item) => {
  let dataStr = window.localStorage.getItem("playData") || "[]";
  let data = JSON.parse(dataStr);
  data[playerIdx.value] = item;
  window.localStorage.setItem("playData", JSON.stringify(data));
};
const clear = (idx) => {
  let dataStr = window.localStorage.getItem("playData") || "[]";
  let data = JSON.parse(dataStr);
  data[idx - 1] = null;
  window.localStorage.setItem("playData", JSON.stringify(data));
};

// let gridData = ref([]);

// 产品要求版
// 监控列表
let page = 1;
let count = 100;
const getMonitorList = async () => {
  let res = await getAnimalMonitorListApi(manageSite);
  if (res.data.code == 200) {
    tableData.value = res.data.data.humanBirdDevices;
    let arr = res.data.data.arDevices;
    arr.forEach(async (item) => {
      item.name = item.deviceName;
      delete item.deviceName;
      let childRes = await getMonitorListApi2(
        item.deviceCode,
        page,
        count,
        item.deviceCode
      );
      item.children = childRes.data.data.list;
      treeData.value.push(item);
    });
  }
};

const defaultProps = {
  children: "children",
  label: "name",
};
// let firstVariable = ref("");
// let secondVariable = ref("");
let firsName = reactive({
  deviceId: "",
  id: "",
});
// ar
const handleNodeClick = (data, node) => {
  firsName.deviceId = data.deviceId;
  firsName.id = data.id;
  let hikIds = data.hikId;
  let deviceId = data.deviceId;
  let channelId = data.id;
  if (node.level > 1) {
    sendDevicePush1({ deviceId, channelId });  // 普通视频
  } else {
    sendDevicePush({ hikIds }); 
  }
};
let ydnlID = ref(""); // 移动鸟类
// 播放
const btn_bf = async (a) => {
  if (spilt.value == 1) {
    btn_xh(1);
  }
  ydnlID.value = a.hikId;
  let hikIds = a.hikId;
  sendDevicePush({ hikIds });
};
// 切换
// let firstVariable = ref("12011700091320000170");
// let secondVariable = ref("12011700091320000171");
let changeVideo = ref("");

const changeGrid = (n) => {
  if (spilt.value == n) return;
  if (n != 1) {
    changeVideo.value = "";
    changeHikId.value = "";
  }
  spilt.value = n;
  if (n == 1) {
    // btn_xh(1)
  } else {
    playerIdx.value = 0; //切换分屏数量后默认选中第一块分屏
  }
};

const btn_xh = (i) => {
  playerIdx.value = i - 1;
  const regex = /\/(\d+)_(\d+)\.live\.flv/;
  if (videoUrl.value[i - 1] != undefined) {
    let matches = videoUrl.value[i - 1].match(regex);
    // console.log(matches, "matches");
    if (matches) {
      setAtab.value = 1;
    } else {
      setAtab.value = 0;
    }
    if (matches && matches.length === 3) {
      // matches[1] 包含第一个数字
      // matches[2] 包含第二个数字
      const firstNumber = matches[1];
      const secondNumber = matches[2];
      // 保存到两个不同的变量中
      firsName.deviceId = firstNumber;
      firsName.id = secondNumber;
    } else {
      // URL不匹配预期的格式
      console.error("URL格式不正确");
    }
  }
};
// AR云台控制
const btn_direction = async (a, b) => {
  if (isChecked.value == true) {
    ElMessage({
      message: "AI识别不允许云台控制~",
      type: "error",
    });
  } else {
    // AR全景云台控制
    if (setAtab.value == 1) {
      let d = 255;
      let res = await getPtzControlApi(firsName.deviceId, firsName.id, a, d);
    } else {
      let d = 50;
      // console.log(ydnlID.value, "ydnlID.value接口");
      let res = await NewgetPtzControlApi2(ydnlID.value, b, d);
      if (a == "stop") {
        let res = await NewgetPtzControlApi3(ydnlID.value, "up", d);
      }
    }
  }

  // console.log(res, "zzz");
};
const btn_toggle = (i) => {
  setAtab.value = i;
};
</script>
<style scoped>
@import "../static/css/About.css";
</style>
<style>
.el-table th.el-table__cell {
  background: rgba(186, 230, 255, 0.2) !important;
  height: 0.38rem;
}

.el-date-editor.el-input {
  width: 100% !important;
}

.el-input {
  --el-input-bg-color: none;
  --el-input-border-color: rgba(102, 225, 252, 0.5);
}

:root {
  --el-bg-color-overlay: linear-gradient(180deg,
      #052548 0%,
      rgba(31, 80, 134, 0.4) 100%);
  --el-text-color-regular: #fff;
  --el-border-color-lighter: rgba(102, 225, 252, 0.5);
  --el-fill-color-light: none;
}

.el-date-picker {
  --el-datepicker-text-color: #fff;
}

.el-picker__popper {
  --el-datepicker-border-color: rgba(102, 225, 252, 0.5);
}

.cell {
  display: flex;
  justify-content: center;
  align-items: center;
  /* color: rgba(186, 230, 255, 0.7); */
}

.el-table__row {
  height: 0.4rem;
  color: #fff;
}

.el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {
  border-bottom: none;
}

.el-table__header {
  color: #fff;
}

.el-overlay-dialog {
  overflow: hidden !important;
}

.el-table {
  /* margin-top: .3rem; */
}

.el-tree {
  background-color: none !important;
}

:root {
  --el-bg-color-overlay: linear-gradient(180deg,
      #052548 0%,
      rgba(31, 80, 134, 0.4) 100%) !important;
  --el-text-color-regular: #fff !important;
  --el-border-color-lighter: rgba(102, 225, 252, 0.5) !important;
  --el-fill-color-light: none !important;
  --el-fill-color-blank: none !important;
}

.tableDiv {
  background-color: none;
  margin-top: 0.3rem;
}

.el-dialog {
  --el-dialog-bg-color: rgba(33, 88, 148, 0.5);
}

.el-table_2_column_4,
.is-leaf,
.el-table__cell {
  color: #fff;
}

.el-dialog__title {
  color: #fff;
}

.redborder {
  border: 2px solid red !important;
}

.btn {
  margin: 0 10px;
}

.btn:hover {
  color: #409eff;
}

.btn.active {
  color: #409eff;
}

.redborder {
  border: 2px solid red !important;
}

.play-box {
  background-color: #000000;
  border: 2px solid #505050;
  display: flex;
  align-items: center;
  justify-content: center;
}

.videoList {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.video-item {
  position: relative;
  width: 15rem;
  height: 10rem;
  margin-right: 1rem;
  background-color: #000000;
}

.video-item-img {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100%;
  height: 100%;
}

.video-item-img:after {
  content: "";
  display: inline-block;
  position: absolute;
  z-index: 2;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 3rem;
  height: 3rem;
  background-image: url("../assets/loading.png");
  background-size: cover;
  background-color: #000000;
}

.video-item-title {
  position: absolute;
  bottom: 0;
  color: #000000;
  background-color: #ffffff;
  line-height: 1.5rem;
  padding: 0.3rem;
  width: 14.4rem;
}

.baidumap {
  width: 100%;
  height: 100%;
  border: none;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

/* 去除百度地图版权那行字 和 百度logo */
.baidumap>.BMap_cpyCtrl {
  display: none !important;
}

.baidumap>.anchorBL {
  display: none !important;
}

/* 产品要求版 */
.righttop_foot {
  overflow-y: scroll;
}

.righttop_foot::-webkit-scrollbar {
  width: 0.04rem;
  /*  设置纵轴（y轴）轴滚动条 */
}

.righttop_foot::-webkit-scrollbar-thumb {
  border-radius: 0px;
  background: transparent;
}

.righttop_foot::-webkit-scrollbar-track {
  border-radius: 0;
  background: transparent;
}

.nobox {
  /* pointer-events: none !important; */
  cursor: not-allowed !important;
}

.no-video {
  display: flex;
  align-items: center;
  justify-content: center;
}

.ai-box {
  position: relative;
}

.zhezhao {
  position: absolute;
  left: 0;
  top: 0;
  background-color: transparent;
  z-index: 999;
}
</style>
